package com.demo.activity;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.VideoView;
import com.demo.R;
import com.demo.domain.Contact;
import com.demo.fragment.EditForm;
import com.demo.fragment.PreviewForm;

import static com.demo.domain.Contact.*;

/**
 * Author: Alexey Tokan
 * Date: 30.07.12
 * Time: 11:22
 */
public class VideoActivity extends Activity {

    private Contact contact;

    private int state = EDIT_STATE;

    public final static int EDIT_STATE = 1;
    public final static int PREVIEW_STATE = 2;

    private final static int SELECT_IMAGE = 1;

    public final static String STATE_EXTRA = "videoActivityState";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set activity layout
        setContentView(R.layout.video_activity);

        // restore contact data if it is represented in savedInstanceState bundle
        if (savedInstanceState != null && savedInstanceState.containsKey(CONTACT)) {
            contact = (Contact) savedInstanceState.get(CONTACT);
        } else {
            contact = new Contact();
        }

        if (savedInstanceState != null && savedInstanceState.containsKey(STATE_EXTRA)) {
            state = savedInstanceState.getInt(STATE_EXTRA);
        }

        // create fragment and replace FrameLayout with id contactEditFragment with it
        // to have possibility to replace this fragment with another.
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        Fragment fragment;
        // choose which fragment will be shown
        if (state == PREVIEW_STATE && savedInstanceState != null && savedInstanceState.containsKey(CONTACT)) {
            fragment = new PreviewForm();
            Bundle bundle = new Bundle();
            bundle.putSerializable(CONTACT, contact);
            fragment.setArguments(bundle);
        } else {
            fragment = new EditForm();
            fragment.setArguments(savedInstanceState);
        }

        fragmentTransaction.replace(R.id.contact_edit_fragment, fragment);
        fragmentTransaction.commit();

        // Invoke videoView to play video
        if (isOnline()) {
            VideoView videoView = (VideoView) findViewById(R.id.video_view);
            videoView.setVideoURI(Uri.parse(getResources().getString(R.string.video_url)));
            videoView.start();
        }
    }

    /**
     * Show contact preview by replacing EditForm  fragment with PreviewFragment. <br/>
     * Invoked by Apply button
     *
     * @param view view element which invoke method
     */
    public void previewForm(View view) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        Bundle bundle = new Bundle();
        ((EditForm) getFragmentManager().findFragmentById(R.id.contact_edit_fragment)).saveFieldToContact(contact);
        bundle.putSerializable(CONTACT, contact);

        Fragment previewFragment = new PreviewForm();
        previewFragment.setArguments(bundle);

        transaction.replace(R.id.contact_edit_fragment, previewFragment);

        transaction.commit();
        this.state = PREVIEW_STATE;
    }

    /**
     * Invoke image select action by creating new Intent with ACTION_PICK
     */
    public void choosePhoto(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        startActivityForResult(intent, SELECT_IMAGE);
    }

    /**
     * Show EditForm fragment by replacing the PreviewFragment</br>
     * Invoked by Back button
     */
    public void back(View view) {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        EditForm editForm = new EditForm();
        Bundle bundle = new Bundle();
        bundle.putSerializable(CONTACT, contact);
        editForm.setArguments(bundle);
        transaction.replace(R.id.contact_edit_fragment, editForm);
        transaction.commit();
        this.state = EDIT_STATE;
    }

    /**
     * Activity result dispatcher. Set contact photo with chosen image
     * if requestCode == SELECT_IMAGE and resultCode is OK
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case SELECT_IMAGE:
                if (resultCode == RESULT_OK) {
                    String path;
                    if ((path = getImagePath(data.getData())) != null) {
                        ImageView photo = (ImageView) findViewById(R.id.contact_photo);
                        photo.setImageURI(Uri.parse(path));
                        contact.setPhoto(path);
                    }
                }
                break;
        }
    }

    /**
     * Fill fragment fields
     *
     * @param contact
     */
    public void fillEditForm(Contact contact) {
        this.contact = contact;
        ((EditForm) getFragmentManager().findFragmentById(R.id.contact_edit_fragment)).fillFields(contact);
    }

    /**
     * Fill contact data with data from fragment fields
     *
     * @param contact
     */
    public void fillContactData(Contact contact) {
        ((EditForm) getFragmentManager().findFragmentById(R.id.contact_edit_fragment)).saveFieldToContact(contact);
    }

    /**
     * Save contact data
     *
     * @param outState
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(CONTACT, contact);
        outState.putInt(STATE_EXTRA, state);
    }

    /**
     * Retrieves image path by uri from system storage.
     *
     * @param uri image uri
     * @return absolute path to image
     */
    public String getImagePath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        String res;
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            res = cursor.getString(column_index);
        } else {
            res = null;
        }
        cursor.close();
        return res;
    }

    /**
     * Check for internet connection
     *
     * @return if internet connection is available or connection return true, else return false
     */
    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        VideoView videoView = (VideoView) findViewById(R.id.video_view);
        videoView.stopPlayback();
    }

    /**
     * Return activity state based on *_STATE constants (EDIT_STATE, PREVIEW_STATE)
     * @return activity state
     */
    public int getState() {
        return state;
    }

}
